import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useEventListener } from '@vueuse/core'

/**
 * 移动端设计器适配组合式函数
 * @returns {Object} 移动端适配功能
 */
export function useMobileDesigner() {
  const isMobile = ref(false)
  const isTablet = ref(false)
  const orientation = ref('portrait')
  const screenSize = ref({ width: 0, height: 0 })
  const safeArea = ref({ top: 0, right: 0, bottom: 0, left: 0 })
  
  // 触摸相关状态
  const touchState = ref({
    isTouch: false,
    startX: 0,
    startY: 0,
    currentX: 0,
    currentY: 0,
    deltaX: 0,
    deltaY: 0,
    scale: 1,
    rotation: 0
  })
  
  const gestureState = ref({
    isPinching: false,
    isRotating: false,
    isDragging: false,
    initialDistance: 0,
    initialAngle: 0
  })

  /**
   * 检测设备类型
   */
  const detectDevice = () => {
    const userAgent = navigator.userAgent.toLowerCase()
    const width = window.innerWidth
    const height = window.innerHeight
    
    // 更新屏幕尺寸
    screenSize.value = { width, height }
    
    // 检测移动设备
    isMobile.value = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent) ||
                     width <= 768
    
    // 检测平板
    isTablet.value = (/ipad/i.test(userAgent) || 
                     (width >= 768 && width <= 1024)) && 
                     !isMobile.value
    
    // 检测方向
    orientation.value = width > height ? 'landscape' : 'portrait'
  }

  /**
   * 获取安全区域
   */
  const updateSafeArea = () => {
    const computedStyle = getComputedStyle(document.documentElement)
    
    safeArea.value = {
      top: parseInt(computedStyle.getPropertyValue('--sat') || '0'),
      right: parseInt(computedStyle.getPropertyValue('--sar') || '0'),
      bottom: parseInt(computedStyle.getPropertyValue('--sab') || '0'),
      left: parseInt(computedStyle.getPropertyValue('--sal') || '0')
    }
  }

  /**
   * 处理触摸开始
   * @param {TouchEvent} event 触摸事件
   */
  const handleTouchStart = (event) => {
    const touch = event.touches[0]
    
    touchState.value = {
      isTouch: true,
      startX: touch.clientX,
      startY: touch.clientY,
      currentX: touch.clientX,
      currentY: touch.clientY,
      deltaX: 0,
      deltaY: 0,
      scale: 1,
      rotation: 0
    }
    
    // 多点触控检测
    if (event.touches.length === 2) {
      const touch1 = event.touches[0]
      const touch2 = event.touches[1]
      
      gestureState.value.isPinching = true
      gestureState.value.initialDistance = getDistance(touch1, touch2)
      gestureState.value.initialAngle = getAngle(touch1, touch2)
    } else {
      gestureState.value.isDragging = true
    }
  }

  /**
   * 处理触摸移动
   * @param {TouchEvent} event 触摸事件
   */
  const handleTouchMove = (event) => {
    event.preventDefault()
    
    if (event.touches.length === 1 && gestureState.value.isDragging) {
      // 单点拖拽
      const touch = event.touches[0]
      
      touchState.value.currentX = touch.clientX
      touchState.value.currentY = touch.clientY
      touchState.value.deltaX = touch.clientX - touchState.value.startX
      touchState.value.deltaY = touch.clientY - touchState.value.startY
      
    } else if (event.touches.length === 2 && gestureState.value.isPinching) {
      // 双点缩放和旋转
      const touch1 = event.touches[0]
      const touch2 = event.touches[1]
      
      const currentDistance = getDistance(touch1, touch2)
      const currentAngle = getAngle(touch1, touch2)
      
      touchState.value.scale = currentDistance / gestureState.value.initialDistance
      touchState.value.rotation = currentAngle - gestureState.value.initialAngle
    }
  }

  /**
   * 处理触摸结束
   * @param {TouchEvent} event 触摸事件
   */
  const handleTouchEnd = (event) => {
    touchState.value.isTouch = false
    gestureState.value.isDragging = false
    gestureState.value.isPinching = false
    gestureState.value.isRotating = false
  }

  /**
   * 获取两点间距离
   * @param {Touch} touch1 触摸点1
   * @param {Touch} touch2 触摸点2
   * @returns {number} 距离
   */
  const getDistance = (touch1, touch2) => {
    const dx = touch2.clientX - touch1.clientX
    const dy = touch2.clientY - touch1.clientY
    return Math.sqrt(dx * dx + dy * dy)
  }

  /**
   * 获取两点间角度
   * @param {Touch} touch1 触摸点1
   * @param {Touch} touch2 触摸点2
   * @returns {number} 角度（弧度）
   */
  const getAngle = (touch1, touch2) => {
    const dx = touch2.clientX - touch1.clientX
    const dy = touch2.clientY - touch1.clientY
    return Math.atan2(dy, dx)
  }

  /**
   * 移动端拖拽适配
   * @param {HTMLElement} element 目标元素
   * @param {Object} options 选项
   */
  const enableMobileDrag = (element, options = {}) => {
    if (!element) return
    
    const {
      onDragStart = () => {},
      onDragMove = () => {},
      onDragEnd = () => {},
      threshold = 10
    } = options
    
    let isDragging = false
    let startPos = { x: 0, y: 0 }
    
    const handleStart = (event) => {
      const touch = event.touches ? event.touches[0] : event
      startPos = { x: touch.clientX, y: touch.clientY }
      
      const moveHandler = (moveEvent) => {
        const currentTouch = moveEvent.touches ? moveEvent.touches[0] : moveEvent
        const deltaX = currentTouch.clientX - startPos.x
        const deltaY = currentTouch.clientY - startPos.y
        const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
        
        if (!isDragging && distance > threshold) {
          isDragging = true
          onDragStart({ startX: startPos.x, startY: startPos.y })
        }
        
        if (isDragging) {
          onDragMove({
            x: currentTouch.clientX,
            y: currentTouch.clientY,
            deltaX,
            deltaY
          })
        }
      }
      
      const endHandler = () => {
        if (isDragging) {
          onDragEnd()
        }
        isDragging = false
        
        document.removeEventListener('touchmove', moveHandler)
        document.removeEventListener('touchend', endHandler)
        document.removeEventListener('mousemove', moveHandler)
        document.removeEventListener('mouseup', endHandler)
      }
      
      document.addEventListener('touchmove', moveHandler, { passive: false })
      document.addEventListener('touchend', endHandler)
      document.addEventListener('mousemove', moveHandler)
      document.addEventListener('mouseup', endHandler)
    }
    
    element.addEventListener('touchstart', handleStart, { passive: false })
    element.addEventListener('mousedown', handleStart)
    
    return () => {
      element.removeEventListener('touchstart', handleStart)
      element.removeEventListener('mousedown', handleStart)
    }
  }

  /**
   * 移动端缩放适配
   * @param {HTMLElement} element 目标元素
   * @param {Object} options 选项
   */
  const enableMobileZoom = (element, options = {}) => {
    if (!element) return
    
    const {
      onZoom = () => {},
      minScale = 0.5,
      maxScale = 3,
      step = 0.1
    } = options
    
    let currentScale = 1
    
    const handleWheel = (event) => {
      event.preventDefault()
      
      const delta = event.deltaY > 0 ? -step : step
      const newScale = Math.max(minScale, Math.min(maxScale, currentScale + delta))
      
      if (newScale !== currentScale) {
        currentScale = newScale
        onZoom(currentScale)
      }
    }
    
    const handlePinch = (event) => {
      if (event.touches.length === 2) {
        event.preventDefault()
        
        const touch1 = event.touches[0]
        const touch2 = event.touches[1]
        const distance = getDistance(touch1, touch2)
        
        if (!gestureState.value.initialDistance) {
          gestureState.value.initialDistance = distance
          return
        }
        
        const scale = distance / gestureState.value.initialDistance
        const newScale = Math.max(minScale, Math.min(maxScale, scale))
        
        if (newScale !== currentScale) {
          currentScale = newScale
          onZoom(currentScale)
        }
      }
    }
    
    element.addEventListener('wheel', handleWheel, { passive: false })
    element.addEventListener('touchmove', handlePinch, { passive: false })
    
    return () => {
      element.removeEventListener('wheel', handleWheel)
      element.removeEventListener('touchmove', handlePinch)
    }
  }

  /**
   * 移动端长按检测
   * @param {HTMLElement} element 目标元素
   * @param {Function} callback 回调函数
   * @param {number} duration 长按时间（毫秒）
   */
  const enableLongPress = (element, callback, duration = 500) => {
    if (!element) return
    
    let timer = null
    let startPos = { x: 0, y: 0 }
    
    const handleStart = (event) => {
      const touch = event.touches ? event.touches[0] : event
      startPos = { x: touch.clientX, y: touch.clientY }
      
      timer = setTimeout(() => {
        callback(event)
      }, duration)
    }
    
    const handleMove = (event) => {
      const touch = event.touches ? event.touches[0] : event
      const deltaX = touch.clientX - startPos.x
      const deltaY = touch.clientY - startPos.y
      const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
      
      // 如果移动距离超过阈值，取消长按
      if (distance > 10) {
        clearTimeout(timer)
      }
    }
    
    const handleEnd = () => {
      clearTimeout(timer)
    }
    
    element.addEventListener('touchstart', handleStart)
    element.addEventListener('mousedown', handleStart)
    element.addEventListener('touchmove', handleMove)
    element.addEventListener('mousemove', handleMove)
    element.addEventListener('touchend', handleEnd)
    element.addEventListener('mouseup', handleEnd)
    
    return () => {
      clearTimeout(timer)
      element.removeEventListener('touchstart', handleStart)
      element.removeEventListener('mousedown', handleStart)
      element.removeEventListener('touchmove', handleMove)
      element.removeEventListener('mousemove', handleMove)
      element.removeEventListener('touchend', handleEnd)
      element.removeEventListener('mouseup', handleEnd)
    }
  }

  /**
   * 获取移动端优化的样式
   */
  const getMobileStyles = computed(() => ({
    // 触摸优化
    touchAction: 'none',
    userSelect: 'none',
    webkitUserSelect: 'none',
    webkitTouchCallout: 'none',
    webkitTapHighlightColor: 'transparent',
    
    // 安全区域适配
    paddingTop: `${safeArea.value.top}px`,
    paddingRight: `${safeArea.value.right}px`,
    paddingBottom: `${safeArea.value.bottom}px`,
    paddingLeft: `${safeArea.value.left}px`,
    
    // 响应式字体
    fontSize: isMobile.value ? '14px' : '16px',
    
    // 触摸目标大小
    minHeight: isMobile.value ? '44px' : 'auto',
    minWidth: isMobile.value ? '44px' : 'auto'
  }))

  /**
   * 获取移动端工具栏配置
   */
  const getMobileToolbarConfig = computed(() => ({
    // 工具栏位置
    position: isMobile.value ? 'bottom' : 'top',
    
    // 按钮大小
    buttonSize: isMobile.value ? 'large' : 'default',
    
    // 显示的工具数量
    maxTools: isMobile.value ? 4 : 8,
    
    // 是否显示文字
    showText: !isMobile.value,
    
    // 是否可折叠
    collapsible: isMobile.value
  }))

  /**
   * 获取移动端面板配置
   */
  const getMobilePanelConfig = computed(() => ({
    // 面板宽度
    width: isMobile.value ? '100%' : '280px',
    
    // 面板高度
    height: isMobile.value ? '50vh' : 'auto',
    
    // 是否全屏显示
    fullscreen: isMobile.value,
    
    // 是否可拖拽
    draggable: !isMobile.value,
    
    // 默认折叠状态
    collapsed: isMobile.value
  }))

  /**
   * 振动反馈
   * @param {string} pattern 振动模式
   */
  const vibrate = (pattern = 'light') => {
    if (!navigator.vibrate) return
    
    const patterns = {
      light: 10,
      medium: 50,
      heavy: 100,
      success: [10, 50, 10],
      error: [50, 50, 50],
      warning: [25, 25, 25]
    }
    
    navigator.vibrate(patterns[pattern] || pattern)
  }

  /**
   * 防止页面滚动
   */
  const preventScroll = (prevent = true) => {
    if (prevent) {
      document.body.style.overflow = 'hidden'
      document.body.style.position = 'fixed'
      document.body.style.width = '100%'
    } else {
      document.body.style.overflow = ''
      document.body.style.position = ''
      document.body.style.width = ''
    }
  }

  // 事件监听
  useEventListener('resize', detectDevice)
  useEventListener('orientationchange', () => {
    setTimeout(detectDevice, 100) // 延迟检测，等待方向改变完成
  })

  // 生命周期
  onMounted(() => {
    detectDevice()
    updateSafeArea()
    
    // 设置CSS变量
    document.documentElement.style.setProperty('--vh', `${window.innerHeight * 0.01}px`)
  })

  onUnmounted(() => {
    preventScroll(false)
  })

  return {
    // 状态
    isMobile,
    isTablet,
    orientation,
    screenSize,
    safeArea,
    touchState,
    gestureState,
    
    // 计算属性
    getMobileStyles,
    getMobileToolbarConfig,
    getMobilePanelConfig,
    
    // 方法
    detectDevice,
    handleTouchStart,
    handleTouchMove,
    handleTouchEnd,
    enableMobileDrag,
    enableMobileZoom,
    enableLongPress,
    vibrate,
    preventScroll
  }
}



